﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SharedGenomics.Core;
using SharedGenomics.Workbench.Core;
using SharedGenomics.Workbench.Views;
using SharedGenomics.Domain;
using SharedGenomics.TextMining;
using SharedGenomics.Workbench.Services;
using SharedGenomics.Annotations;

namespace SharedGenomics.Workbench.Presenters
{
    public class TextMinedPublicationsPresenter : AnnotationPresenter<PublicationsAnnotation>
    {
        public TextMinedPublicationsPresenter(ITextMinedPublicationsView view)
            : base(view)
        {
            this.PublicationsView = view;
        }

        protected override void OnAnnotationSet(PublicationsAnnotation annotation)
        {
            annotation.ThrowIfNull("annotation");
            annotation.Publications.ThrowIfNull<ArgumentException>("Cannot display publications - collection is null");

            this.Publications = annotation.Publications;
        }

        private IList<Publication> Publications
        {
            set
            {
                //create string of publication titles
                IList<Publication> publications = value;

                int publicationCount = publications.Count;
                StringBuilder text = new StringBuilder();

                foreach (Publication p in publications)
                {
                    if (publicationCount-- > 1)
                    {
                        text.AppendLine(p.Title);
                    }
                    else
                    {
                        text.Append(p.Title);
                    }
                }

                TermineProxy proxy = new TermineProxy();
                ScoredTermCollection terms = proxy.Analyse(text.ToString());

                PublicationTitleMiner miner = new PublicationTitleMiner(terms);

                //mine the titles of all publications
                foreach (Publication p in publications)
                {
                    miner.MinePublication(p);
                }

                this.PublicationsView.TitleMiner = miner;
            }
        }

        private ITextMinedPublicationsView PublicationsView { get; set; }
    }
}
